const newsApi = require('../../../api/familynews');
const { getImageUrl } = require('../../../utils/image');

Page({
  data: {
    newsList: [],
    loading: false,
    hasMore: true,
    page: 1,
    pageSize: 10,
    clanId: null,
    total: 0,
    refreshing: false,
    likeStatus: {}, // 存储用户对每条动态的点赞状态
    activeType: '', // 当前激活的筛选类型
    showTopBtn: false, // 是否显示回到顶部按钮
  },

  onLoad(options) {
    // 可以从options中获取可能的过滤条件
    if (options.clanId) {
      this.setData({ clanId: options.clanId });
    }
    
    // 如果传入了类型参数，设置激活筛选类型
    if (options.type) {
      this.setData({ activeType: options.type });
    }
    
    // 加载数据
    this.loadNewsList(true);
    
    // 监听页面滚动事件
    wx.onPageScroll(this.onPageScroll);
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      refreshing: true,
      page: 1,
      hasMore: true
    });
    this.loadNewsList(true).then(() => {
      wx.stopPullDownRefresh();
      this.setData({ refreshing: false });
    }).catch(() => {
      wx.stopPullDownRefresh();
      this.setData({ refreshing: false });
    });
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadNewsList(false);
    }
  },

  // 类型筛选
  filterByType(e) {
    const type = e.currentTarget.dataset.type;
    
    // 如果点击当前已激活的类型，不做处理
    if (this.data.activeType === type) return;
    
    this.setData({
      activeType: type,
      page: 1,
      hasMore: true,
      newsList: []
    });
    
    // 重新加载数据
    this.loadNewsList(true);
  },

  // 加载家族动态列表
  loadNewsList(isRefresh = false) {
    if (this.data.loading) return Promise.reject('正在加载中');
    
    this.setData({ loading: true });
    
    // 如果是刷新，重置页码
    if (isRefresh) {
      this.setData({ page: 1 });
    }
    
    const params = {
      page: this.data.page,
      size: this.data.pageSize
    };
    
    // 添加可能的筛选条件
    if (this.data.clanId) {
      params.clanId = this.data.clanId;
    }
    
    // 添加类型筛选
    if (this.data.activeType) {
      params.type = this.data.activeType;
    }
    
    // 使用API调用获取动态列表
    return newsApi.getNewsList(params)
      .then(res => {
        // 处理返回数据
        const { records, total, current, size } = res;
        const formattedData = records.map(item => this.formatNewsItem(item));
        
        // 设置数据
        this.setData({
          newsList: isRefresh ? formattedData : [...this.data.newsList, ...formattedData],
          total,
          hasMore: current * size < total,
          page: current + 1,
          loading: false
        });
        
        // 加载成功后，获取点赞状态
        this.loadLikeStatus(formattedData.map(item => item.id));
        
        // 如果是刷新操作，显示成功提示
        if (isRefresh && !this.data.refreshing) {
          wx.showToast({
            title: '刷新成功',
            icon: 'success',
            duration: 1000
          });
        }
        
        return formattedData;
      })
      .catch(err => {
        console.error('加载家族动态列表失败:', err);
        this.setData({ loading: false });
        wx.showToast({ title: err.msg || '加载失败', icon: 'none' });
        return Promise.reject(err);
      });
  },

  // 获取用户对动态的点赞状态
  loadLikeStatus(newsIds) {
    if (!newsIds || newsIds.length === 0) return;
    
    newsApi.getUserLikes(newsIds)
      .then(res => {
        const likeStatus = {};
        (res || []).forEach(item => {
          likeStatus[item.newsId] = item.liked;
        });
        
        this.setData({ likeStatus });
      })
      .catch(err => {
        console.error('获取点赞状态失败:', err);
        // 不提示错误，因为这不是核心功能
      });
  },

  // 处理动态数据格式
  formatNewsItem(item) {
    return {
      id: item.id,
      title: item.title,
      description: item.description,
      content: item.content,
      image: getImageUrl(item.image),
      type: item.type,
      authorName: item.authorName,
      authorAvatar: getImageUrl(item.authorAvatar),
      viewCount: item.viewCount || 0,
      likeCount: item.likeCount || 0,
      createdAt: this.formatTime(item.createdAt),
      clanName: item.clanName || '',
      clanId: item.clanId
    };
  },

  // 格式化时间
  formatTime(isoTime) {
    if (!isoTime) return '';
    
    try {
      const date = new Date(isoTime);
      if (isNaN(date.getTime())) {
        return isoTime;
      }
      
      const now = new Date();
      const diff = Math.floor((now - date) / 1000); // 秒数差
      
      if (diff < 60) {
        return '刚刚';
      } else if (diff < 3600) {
        return Math.floor(diff / 60) + '分钟前';
      } else if (diff < 86400) {
        return Math.floor(diff / 3600) + '小时前';
      } else if (diff < 2592000) {
        return Math.floor(diff / 86400) + '天前';
      } else {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      }
    } catch (e) {
      console.error('时间格式化错误:', e);
      return isoTime || '';
    }
  },

  // 点赞
  onLike(e) {
    const { id, index } = e.currentTarget.dataset;
    const liked = this.data.likeStatus[id];
    
    // 如果已点赞，则取消点赞，否则点赞
    const likeMethod = liked ? newsApi.unlikeNews : newsApi.likeNews;
    
    likeMethod(id)
      .then(res => {
        // 更新点赞状态
        const likeStatus = { ...this.data.likeStatus };
        likeStatus[id] = !liked;
        
        // 更新点赞数
        const newsList = [...this.data.newsList];
        newsList[index].likeCount += liked ? -1 : 1;
        
        this.setData({
          likeStatus,
          newsList
        });
        
        wx.vibrateShort(); // 震动反馈
        
        // 显示反馈
        wx.showToast({
          title: liked ? '已取消点赞' : '点赞成功',
          icon: 'success',
          duration: 1000
        });
      })
      .catch(err => {
        wx.showToast({ title: err.msg || (liked ? '取消点赞失败' : '点赞失败'), icon: 'none' });
      });
  },

  // 页面滚动监听
  onPageScroll(e) {
    // 当页面滚动超过一定距离后，显示回到顶部按钮
    const scrollTop = e.scrollTop;
    const showTopBtn = scrollTop > 300;
    
    // 避免频繁setData
    if (showTopBtn !== this.data.showTopBtn) {
      this.setData({ showTopBtn });
    }
  },
  
  // 回到顶部
  goToTop() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    });
  },
  
  // 查看动态详情
  viewDetail(e) {
    const { id } = e.currentTarget.dataset;
    
    // 记录浏览
    newsApi.increaseViewCount(id).catch(err => {
      console.error('增加浏览量失败', err);
    });
    
    wx.navigateTo({
      url: `/pages/familynews/detail/index?id=${id}`
    });
  },
  
  // 页面卸载时清理事件监听
  onUnload() {
    // 微信小程序不需要手动移除页面滚动监听
    // 页面销毁时，监听会自动移除
  }
}); 